package com.yswl.pri.common.utils;

import android.app.Activity;
import android.text.TextUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import yswl.com.klibrary.util.ToastUtil;

/**
 * Created by qiaopeng@yuntetong.net on 2018/3/13.
 */

public class MResultUtil {
    public static final String TAG = "ResultUtil";
    /**
     * 数据说明标志
     **/
    public static final String MSG = "message";
    /**
     * 数据标志
     **/
    public static final String VALUE = "value";
    public static final String CODE = "code";

    public static boolean isSuccess(JSONObject json, Activity context, boolean notice) {
        return isSuccess(json, notice, context);
    }

    public static boolean isSuccess(JSONObject json, Activity context) {
        return isSuccess(json, true, context);
    }

    public static boolean isSuccess(JSONObject json) {
        return isSuccess(json, true, null);
    }

    public static boolean isCode200(JSONObject json) {
        if (json == null)
            return false;
        return json.optInt(CODE, -1) == 200;
    }

    private static boolean isCode401(JSONObject json) {
        return json != null && json.optInt(CODE, -1) == 401;
    }

    public static boolean isSuccess(JSONObject json, boolean notice, Activity context) {
        if (json == null)
            return false;
        if (!(isCode200(json))) {
            if (isCode401(json)) {
                //TODO list
            }
            if (notice) {
                String msg = json.optString(MSG);
                if (TextUtils.isEmpty(msg) || "null".equals(msg)) {
                    msg = "请求异常";
                }
                ToastUtil.showToast(msg);
            }
            return false;
        }
        return true;
    }

    public static JSONObject getValueJSONObj(JSONObject json) {
        return json.optJSONObject("value");
    }

    public static JSONArray getValueJSONArr(JSONObject json) {
        return json.optJSONArray("value");
    }

    public static Object getValue(JSONObject json) {
        return json.opt("value");
    }

    public static boolean isValueNotNull(JSONObject json) {
        if (json == null) {
            return false;
        }
        if (json.opt("value") != null) {
            return true;
        }
        return false;
    }

    public static JSONArray getArrayObjDATA(JSONObject json, String key) {
        Object obj = getDATA(json, key);
        if (obj instanceof JSONArray) {
            return (JSONArray) obj;
        }
        return null;
    }

    public static Object getDATA(JSONObject json, String key) {
        if (json == null)
            return null;
        return json.opt(key);
    }
}